﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Collections.ObjectModel;

namespace EntityNorthwind
{
    /// <summary>
    /// Shopping Cart example.
    /// This is an example of creating a separate class that wraps persistent objects.
    /// This class, conveniently, addresses a limitation in the current builds in that
    /// we do not support mapping identifying relationships (relationships between tables
    /// where the primary key of one table is the foreign key of the relationship) this 
    /// will be supported in future builds before Orcas RTM.
    /// </summary>
    public class ShoppingCart
    {

        private ShoppingCart(Order order, EntityNorthwindContext northwind)
        {
            this.order = order;
            this.northwind = northwind;
        }

        public static ShoppingCart FindByID(int id, EntityNorthwindContext northwind)
        {
            Order order = northwind.Orders.Where("it.OrderId = @id", new ObjectParameter("id", id)).First();
            return new ShoppingCart(order, northwind);
        }

        public static ShoppingCart CreateCart(EntityNorthwindContext northwind, Customer customer, Employee employee)
        {
            Order order = new Order();
            order.Customer = customer;
            order.Employee = employee;
            order.OrderDate = DateTime.Now;
            northwind.AddObject(order);
            northwind.SaveChanges();
            return new ShoppingCart(order, northwind);
        }

        public int ID
        {
            get
            {
                return this.order.OrderID;
            }
        }

        public Order OrderInfo
        {
            get
            {
                return this.order;
            }
        }


        public ObjectQuery<OrderDetail> Lines
        {
            get
            {
                return northwind.OrderDetails.Where("it.OrderId = @OrderId", new ObjectParameter("OrderId", order.OrderID));
            }
        }

        public void AddLine(int productID, decimal unitPrice, short quantity, float discount)
        {
            OrderDetail line = new OrderDetail(order.OrderID, productID, unitPrice, quantity, discount);
            northwind.AddObject(line);
        }


        private Order order;
        private EntityNorthwindContext northwind;
    }
}
       
